# -*- coding: utf-8 -*-
#高级特性----返回函数，高阶函数除了可以接受函数作为参数外，还可以把函数作为结果值返回。
import io
import sys
from functools import reduce

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

def lazy_sum(*args):
	def sum():
		ax = 0
		for i in args:
			ax = ax + i
		return ax
	return sum
f1 = lazy_sum(1,2,3,4,5,6)
f2 = lazy_sum(1,2,3,4,5,6)
f3 = lazy_sum(1,2,3)

print(f1())
print(f1 == f2)
print(f3())

# 返回闭包时牢记一点：返回函数不要引用任何循环变量，或者后续会发生变化的变量。 
def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())


def createCounter():
	def ge():
		i = 1
		while True:
			yield i
			i += 1
		return i
	g = ge()
	def counter():
		return next(g)
	return counter


# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('测试通过!')
else:
    print('测试失败!')